import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

import { CSSTransition, TransitionGroup } from 'react-transition-group';

import Message from './message';

import styles from './index.less';
import './transition.less';

interface MessageApi {
  info: (text: string) => void;
  success: (text: string) => void;
  warning: (text: string) => void;
  error: (text: string) => void;
}

type MessageType = 'info' | 'success' | 'danger' | 'warning';

interface Message {
  text: string;
  key: string;
  type: MessageType;
}

let seed = 0;
const now = Date.now();
const getUuid = (): string => {
  const id = seed;
  seed += 1;
  return `MESSAGE_${now}_${id}`;
};

let add: (message: Message) => void;

const MessageContainer = () => {
  const [message, setMessage] = useState<Message[]>([]);
  const timeout = 3 * 1000;
  const maxCount = 10;

  const remove = (message: Message) => {
    const { key } = message;
    setMessage((prevMessage) => {
      return prevMessage.filter(({ key: itemKey }) => key !== itemKey);
    });
  };

  add = (message: Message) => {
    setMessage((prevMessage) => [...prevMessage, message]);

    setTimeout(() => {
      remove(message);
    }, timeout);
  };

  useEffect(() => {
    if (message.length > maxCount) {
      const [firstNotice] = message; //索引0的数据
      remove(firstNotice);
    }
  }, [message]);
  return (
    <div className={styles.messageContainer}>
      <TransitionGroup>
        {message.map(({ text, key, type }) => (
          <CSSTransition key={key} timeout={500} classNames="message-item">
            <Message key={key} type={type} text={text} />
          </CSSTransition>
        ))}
      </TransitionGroup>
    </div>
  );
};

let el = document.querySelector('#message-wrapper');
if (!el) {
  el = document.createElement('div');
  el.className = 'message-wrapper';
  el.id = 'message-wrapper';
  document.body.append(el);
}

ReactDOM.render(<MessageContainer />, el);

const api: MessageApi = {
  info: (text) => {
    add({
      text,
      key: getUuid(),
      type: 'info',
    });
  },
  success: (text) => {
    add({
      text,
      key: getUuid(),
      type: 'success',
    });
  },
  warning: (text) => {
    add({
      text,
      key: getUuid(),
      type: 'warning',
    });
  },
  error: (text) => {
    add({
      text,
      key: getUuid(),
      type: 'danger',
    });
  },
};

export default api;
